// 源插件
import React, { PureComponent } from 'react';
import { DateDiff, DateStamp, FormatnumberZero, Mover, NumberDivide } from '@/function.js';
// 视图插件
import { Button, Card, Form, message, Modal, notification, Row, Col, Popconfirm } from 'antd';
// 外部组件
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTablePro from '@/components/UpgradeStandardTable/StandardTablePro';
import { connect } from 'dva';
import html2canvas from 'html2canvas';
import _findIndex from 'lodash/findIndex';
import AddModal from './AddModal';
import AddStockModal from './AddStockModal';
import UpdateModal from './UpdateModal';
import UpdateStockModal from './UpdateStockModal';
// css OR less预编译器

// 图片

/**
 *  Describe:数据连接
 */

@connect(({ lastTrade, loading }) => ({
  lastTrade,
  loading: loading.models.lastTrade,
}))
@Form.create()
class LastTrade extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    dataSourceSB: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceSS: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceO: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceCpb: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceEx: {
      data: [],
      total: [],
      code: 0,
    },
    cropFlag: false,
    buyVisible: false,
    sellVisible: false,
    addStockVisible: false,
    exVisible: false,
    updateOptionVisible: false,
    updateStockVisible: false,
    row: {},
    loading:false,
  };

  HtmlCrop() {
    const that = this;
    const key = `open${Date.now()}`;
    const { dispatch } = that.props;
    const btn = (
      <Button
        type="primary"
        size="small"
        onClick={() => {
          notification.close(key);
          that.setState({
            cropFlag: true,
          });
          html2canvas(document.getElementById('crop'), {
            scale: 1,
          }).then(canvas => {
            const imgUrl = canvas.toDataURL();
            // dataURLtoFile(imgUrl, 'aaa')
            // 获取截图base64
            dispatch({
              type: 'fourfunds/CommitImage',
              payload: {
                base64Str: imgUrl,
                jobName: '',
              },
              callback: res => {
                that.setState({
                  cropFlag: false,
                });
              },
            });
          });
        }}
      >
        确定
      </Button>
    );
    notification.open({
      message: 'Notification Title',
      description: '是否全部删除',
      btn,
      key,
      onClose: close,
    });
  }

  buy() {
    this.setState({
      buyVisible: true,
    });
  }

  sell() {
    const that = this;
    const { dispatch } = that.props;

    this.setState(
      {
        sellVisible: true,
      },
      () => {
        dispatch({
          type: 'lastTrade/GetCpbLastPosition',
          payload: 1,
          callback: res => {
            that.setState({
              dataSourceCpb: {
                code: res.code,
                title: false,
                data: res.data,
                total: [],
                columns: [
                  {
                    title: '期权代码',
                    dataIndex: 'optionCode',
                    width: 110,
                    type: 'string',
                    sorter: true,
                    search: true,
                  },
                  {
                    title: '期权类型',
                    width: 80,
                    dataIndex: 'optionType',
                    type: 'number',
                    // search: true,
                    filters: [
                      {
                        text: 'SP',
                        value: '1',
                      },
                      {
                        text: 'SC',
                        value: '2',
                      },
                      {
                        text: 'BP',
                        value: '3',
                      },
                      {
                        text: 'BC',
                        value: '4',
                      },
                    ],
                    render: (value, row, index) => {
                      if (value === 1) {
                        return 'SP';
                      }
                      if (value === 2) {
                        return 'SC';
                      }
                      if (value === 3) {
                        return 'BP';
                      }
                      if (value === 4) {
                        return 'BC';
                      }
                    },
                  },
                  {
                    title: '数量(可修改)',
                    width: 75,
                    dataIndex: 'optionCount',
                    type: 'number',
                    sorter: true,
                    editable: true,
                  },
                  {
                    title: '成本价',
                    dataIndex: 'premium',
                    type: 'number',
                    width: 80,
                    sorter: true,
                  },
                  {
                    title: '输入卖出价(可修改)',
                    dataIndex: 'nowPrice',
                    type: 'number',
                    width: 80,
                    editable: true,
                  },
                  {
                    title: '操作',
                    width: 80,
                    render: (value, row, index) => {
                      if (row.flag !== 1) {
                        return (
                          <a href="javascript:void(0);" onClick={this.sellout.bind(this, row)}>
                            卖出
                          </a>
                        );
                      }
                      return (
                        <a href="javascript:void(0);" onClick={this.sellout.bind(this, row)}>
                          卖出(已操作)
                        </a>
                      );
                    },
                  },
                ],
              },
            });
          },
        });
      }
    );
  }

  sellout(row) {
    const that = this;
    const { dispatch } = that.props;
    dispatch({
      type: 'lastTrade/AddCtbOptionTrade',
      payload: {
        id: row.id,
        nowPrice: row.nowPrice,
        optionCount: row.optionCount,
      },
      callback: res => {
        const { data } = that.state.dataSourceCpb;
        const index = _findIndex(data, function(data) {
          return data.id === row.id;
        });
        data[index].flag = 1;
      },
    });
  }

  handleSaveCqb(row, values) {
    const { data } = this.state.dataSourceCpb;
    const index = _findIndex(data, function(data) {
      return data.id === row.id;
    });
    data[index].nowPrice = parseFloat(values.nowPrice) || row.nowPrice;
    data[index].optionCount = parseFloat(values.optionCount) || row.optionCount;
    this.setState({
      dataSourceCpb: { ...this.state.dataSourceCpb, data },
    });
  }

  exercise() {
    const that = this;
    const { dispatch } = that.props;

    this.setState(
      {
        exVisible: true,
      },
      () => {
        dispatch({
          type: 'lastTrade/GetAllLastOptionPosition',
          payload: 1,
          callback: res => {
            that.setState({
              dataSourceEx: {
                code: res.code,
                title: false,
                data: res.data,
                total: [],
                columns: [
                  {
                    title: '期权代码',
                    dataIndex: 'optionCode',
                    width: 110,
                    type: 'string',
                    sorter: true,
                    search: true,
                  },
                  {
                    title: '银行',
                    width: 80,
                    dataIndex: 'bank',
                    type: 'number',
                    // search: true,
                    filters: [
                      {
                        text: '瑞银',
                        value: '1',
                      },
                      {
                        text: '花旗',
                        value: '2',
                      },
                    ],
                    render: (value, row, index) => {
                      if (value === 1) {
                        return '瑞银';
                      }
                      if (value === 2) {
                        return '花旗';
                      }
                      return value;
                    },
                  },
                  {
                    title: '期权类型',
                    width: 80,
                    dataIndex: 'optionType',
                    type: 'number',
                    // search: true,
                    filters: [
                      {
                        text: 'SP',
                        value: '1',
                      },
                      {
                        text: 'SC',
                        value: '2',
                      },
                      {
                        text: 'BP',
                        value: '3',
                      },
                      {
                        text: 'BC',
                        value: '4',
                      },
                    ],
                    render: (value, row, index) => {
                      if (value === 1) {
                        return 'SP';
                      }
                      if (value === 2) {
                        return 'SC';
                      }
                      if (value === 3) {
                        return 'BP';
                      }
                      if (value === 4) {
                        return 'BC';
                      }
                    },
                  },
                  {
                    title: '数量(可修改)',
                    width: 75,
                    dataIndex: 'optionCount',
                    type: 'number',
                    sorter: true,
                    editable: true,
                  },
                  {
                    title: '成本价',
                    dataIndex: 'premium',
                    type: 'number',
                    width: 80,
                    sorter: true,
                  },
                  // {
                  //   title: '输入卖出价(可修改)',
                  //   dataIndex: 'nowPrice',
                  //   type:'number',
                  //   width:80,
                  //   editable:true
                  // },
                  {
                    title: '操作',
                    width: 80,
                    render: (value, row, index) => {
                      if (row.flag !== 1) {
                        return (
                          <a href="javascript:void(0);" onClick={this.exerciseOut.bind(this, row)}>
                            行权
                          </a>
                        );
                      }
                      return (
                        <a href="javascript:void(0);" onClick={this.exerciseOut.bind(this, row)}>
                          行权(已操作)
                        </a>
                      );
                    },
                  },
                ],
              },
            });
          },
        });
      }
    );
  }

  exerciseOut(row) {
    const that = this;
    const { dispatch } = that.props;
    dispatch({
      type: 'lastTrade/UpdateOptionExercise',
      payload: {
        id: row.id,
        count: row.optionCount,
      },
      callback: res => {
        const { data } = that.state.dataSourceEx;
        const index = _findIndex(data, function(data) {
          return data.id === row.id;
        });
        data[index].flag = 1;
      },
    });
  }

  handleSaveEx(row, values) {
    const { data } = this.state.dataSourceEx;
    const index = _findIndex(data, function(data) {
      return data.id === row.id;
    });
    data[index].optionCount = parseFloat(values.optionCount) || row.optionCount;
    this.setState({
      dataSourceEx: { ...this.state.dataSourceEx, data },
    });
  }

  closeBuyVisbile() {
    const that = this;
    this.setState(
      {
        buyVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }

  closeSellVisbile() {
    const that = this;
    this.setState(
      {
        sellVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }

  closeExerciseVisbile() {
    const that = this;
    this.setState(
      {
        exVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }

  sync() {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'lastTrade/Synchronization',
      callback: res => {
        that.dataSourceChange();
      },
    });
  }

  addStock() {
    this.setState({
      addStockVisible: true,
    });
  }

  closeAddStockVisbile() {
    const that = this;
    this.setState(
      {
        addStockVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }

  generatePosition() {
    const { dispatch } = this.props;
    const that = this;
    that.setState({
      loading:true,
    });
    dispatch({
      type: 'lastTrade/GetGeneratePosition',
      callback: () => {
        that.setState({
          loading:false,
        })
      }
    });
  }

  generateWorth() {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'lastTrade/GetGenerateFundWorth',
    });
  }

  render() {
    const {
      cropFlag,
      dataSourceEx,
      exVisible,
      dataSourceO,
      dataSourceSB,
      dataSourceSS,
      dataSourceCpb,
      buyVisible,
      sellVisible,
      addStockVisible,
      updateOptionVisible,
      updateStockVisible,
      row,
      loading
    } = this.state;
    const b = 0;
    return (
      <PageHeaderWrapper>
        <Card>
          <Row>
            <Col>
              <Button style={{ margin: 8 }} onClick={this.sync.bind(this)}>
                同步瑞银操作
              </Button>
              <Button type="primary" style={{ margin: 8 }} onClick={this.buy.bind(this)}>
                买入花旗期权
              </Button>
              <Button type="primary" style={{ margin: 8 }} onClick={this.sell.bind(this)}>
                卖出花旗期权
              </Button>
              <Button type="primary" style={{ margin: 8 }} onClick={this.exercise.bind(this)}>
                期权行权
              </Button>
              <Button style={{ margin: 8 }} onClick={this.addStock.bind(this)}>
                添加花旗股票
              </Button>
              <Button style={{ margin: 8 }} onClick={this.generatePosition.bind(this)} loading={loading}>
                生成持仓
              </Button>
              <Button style={{ margin: 8 }} onClick={this.generateWorth.bind(this)}>
                生成净值
              </Button>
            </Col>
          </Row>
          <br />
          <StandardTablePro dataSource={dataSourceSB} /> <br />
          <StandardTablePro dataSource={dataSourceSS} />
          <br />
          <StandardTablePro dataSource={dataSourceO} />
          <Modal
            destroyOnClose
            title="添加"
            visible={sellVisible}
            onCancel={this.closeSellVisbile.bind(this)}
            width="80%"
            centered
            footer={false}
          >
            <StandardTablePro
              dataSource={dataSourceCpb}
              handleSave={this.handleSaveCqb.bind(this)}
            />
          </Modal>
          <Modal
            destroyOnClose
            title="添加"
            visible={exVisible}
            onCancel={this.closeExerciseVisbile.bind(this)}
            width="80%"
            centered
            footer={false}
          >
            <StandardTablePro dataSource={dataSourceEx} handleSave={this.handleSaveEx.bind(this)} />
          </Modal>
          <AddModal closeVisbile={this.closeBuyVisbile.bind(this)} visible={buyVisible} />
          <AddStockModal
            closeVisbile={this.closeAddStockVisbile.bind(this)}
            visible={addStockVisible}
          />
          <UpdateModal
            closeVisbile={this.closeUpdateOptionVisbile.bind(this)}
            visible={updateOptionVisible}
            row={row}
          />
          <UpdateStockModal
            closeVisbile={this.closeUpdateStockVisbile.bind(this)}
            visible={updateStockVisible}
            row={row}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }

  dataSourceChange() {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'lastTrade/StockTradeList',
      callback: res => {
        const buyList = [];
        const sellList = [];
        for (let i = 0; i < res.list.stockTradeList.length; i++) {
          const item = res.list.stockTradeList[i];
          if (item.operateType === 1) {
            buyList.push(item);
          } else {
            sellList.push(item);
          }
        }
        that.setState({
          dataSourceSB: {
            title: '股票（买）',
            data: buyList,
            code: res.code,
            total: [],
            columns: [
              {
                title: '代码',
                dataIndex: 'stock',
                width: 110,
                type: 'string',
                sorter: true,
                search: true,
              },
              {
                title: '方向',
                dataIndex: 'operateType',
                type: 'string',
                width: 60,
                filters: [
                  {
                    text: '买',
                    value: '1',
                  },
                  {
                    text: '卖',
                    value: '0',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return '买';
                  }
                  if (value === 0) {
                    return '卖';
                  }
                  return value;
                },
              },

              {
                title: '数量',
                dataIndex: 'operateNum',
                type: 'number',
                width: 80,
                sorter: true,
              },
              {
                title: '当前价格',
                width: 80,
                dataIndex: 'nowPrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '买入价格',
                width: 80,
                dataIndex: 'operatePrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '本金市值',
                width: 80,
                dataIndex: 'costMarketValue',
                type: 'number',
                sorter: true,
              },
              {
                title: '盈亏百分比',
                width: 80,
                dataIndex: 'profitPercent',
                type: 'number',
                sorter: true,
                render: (value, row, index) => {
                  return <span>{`${FormatnumberZero(value * 100, 2)}%`}</span>;
                },
              },
              {
                title: '利润',
                width: 80,
                dataIndex: 'profit',
                type: 'number',
                sorter: true,
              },
              {
                title: '银行',
                width: 80,
                dataIndex: 'bank',
                type: 'number',
                // search: true,
                filters: [
                  {
                    text: '瑞银',
                    value: '1',
                  },
                  {
                    text: '花旗',
                    value: '2',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return '瑞银';
                  }
                  if (value === 2) {
                    return '花旗';
                  }
                  return value;
                },
              },
              {
                title: '标识',
                dataIndex: 'aqDqMark',
                type: 'string',
                width: 60,
                filters: [
                  {
                    text: '股票',
                    value: '0',
                  },
                  {
                    text: 'AQDQ',
                    value: '1',
                  },
                  {
                    text: '期权',
                    value: '2',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return 'AQDQ';
                  }
                  if (value === 2) {
                    return '期权行权';
                  }
                  if (value === 0) {
                    return '股票';
                  }
                  return value;
                },
              },
              {
                title: '操作',
                width: 80,
                render: (value, row, index) => {
                  return (
                    <div>
                      <a href="javascript:void(0);" onClick={this.updateStock.bind(this, row)}>
                        编辑
                      </a>{' '}
                      |{' '}
                      <a href="javascript:void(0);" onClick={this.deleteStock.bind(this, row)}>
                        删除
                      </a>
                    </div>
                  );
                },
              },
            ],
          },
          dataSourceSS: {
            title: '股票（卖）',
            data: sellList,
            code: res.code,
            total: [],
            columns: [
              {
                title: '代码',
                dataIndex: 'stock',
                width: 110,
                type: 'string',
                sorter: true,
                search: true,
              },
              {
                title: '方向',
                dataIndex: 'operateType',
                type: 'string',
                width: 60,
                filters: [
                  {
                    text: '买',
                    value: '1',
                  },
                  {
                    text: '卖',
                    value: '0',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return '买';
                  }
                  if (value === 0) {
                    return '卖';
                  }
                  return value;
                },
              },

              {
                title: '数量',
                dataIndex: 'operateNum',
                type: 'number',
                width: 80,
                sorter: true,
              },
              {
                title: '卖出价格',
                width: 80,
                sorter: true,
                dataIndex: 'operatePrice',
                type: 'number',
              },
              {
                title: '成本价格',
                width: 80,
                sorter: true,
                dataIndex: 'costPrice',
                type: 'number',
              },
              {
                title: '本金市值',
                width: 80,
                dataIndex: 'costMarketValue',
                type: 'number',
                sorter: true,
              },
              {
                title: '盈亏百分比',
                width: 80,
                dataIndex: 'profitPercent',
                type: 'number',
                sorter: true,
                render: (value, row, index) => {
                  return <span>{`${FormatnumberZero(value * 100, 2)}%`}</span>;
                },
              },
              {
                title: '利润',
                width: 80,
                dataIndex: 'profit',
                type: 'number',
                sorter: true,
              },
              {
                title: '银行',
                width: 80,
                dataIndex: 'bank',
                type: 'number',
                // search: true,
                filters: [
                  {
                    text: '瑞银',
                    value: '1',
                  },
                  {
                    text: '花旗',
                    value: '2',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return '瑞银';
                  }
                  if (value === 2) {
                    return '花旗';
                  }
                  return value;
                },
              },
              {
                title: '标识',
                dataIndex: 'aqDqMark',
                type: 'string',
                width: 60,
                filters: [
                  {
                    text: '股票',
                    value: '0',
                  },
                  {
                    text: 'AQDQ',
                    value: '1',
                  },
                  {
                    text: '期权',
                    value: '2',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return 'AQDQ';
                  }
                  if (value === 2) {
                    return '期权行权';
                  }
                  if (value === 0) {
                    return '股票';
                  }
                  return value;
                },
              },
              {
                title: '操作',
                width: 80,
                render: (value, row, index) => {
                  return (
                    <div>
                      <a href="javascript:void(0);" onClick={this.updateStock.bind(this, row)}>
                        编辑
                      </a>{' '}
                      |{' '}
                      <a href="javascript:void(0);" onClick={this.deleteStock.bind(this, row)}>
                        删除
                      </a>
                    </div>
                  );
                },
              },
            ],
          },
        });
      },
    });
    dispatch({
      type: 'lastTrade/GetLastTradeList',
      callback: res => {
        that.setState({
          dataSourceO: {
            title: '期权',
            data: res.data,
            code: res.code,
            total: [],
            columns: [
              {
                title: '代码',
                dataIndex: 'code',
                width: 110,
                type: 'string',
                sorter: true,
                search: true,
              },
              {
                title: '买卖方向',
                dataIndex: 'typeName',
                type: 'string',
                width: 60,
                search: true,
              },
              {
                title: '执行价',
                width: 80,
                dataIndex: 'strikePrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '数量',
                dataIndex: 'optionCount',
                type: 'number',
                width: 80,
                sorter: true,
              },
              {
                title: '敞口',
                width: 80,
                dataIndex: 'positionSize',
                type: 'number',
                sorter: true,
              },
              {
                title: '现价',
                dataIndex: 'nowPrice',
                type: 'number',
                width: 80,
                sorter: true,
              },
              {
                title: '到期日',
                width: 80,
                dataIndex: 'expiry',
                type: 'date',
                sorter: true,
                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
              {
                title: '成本价',
                width: 75,
                dataIndex: 'costPrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '收益',
                width: 80,
                dataIndex: 'profit',
                type: 'number',
                sorter: true,
              },
              {
                title: '银行',
                width: 80,
                dataIndex: 'bank',
                type: 'number',
                // search: true,
                filters: [
                  {
                    text: '瑞银',
                    value: '1',
                  },
                  {
                    text: '花旗',
                    value: '2',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return '瑞银';
                  }
                  if (value === 2) {
                    return '花旗';
                  }
                  return value;
                },
              },
              {
                title: '操作',
                width: 80,
                render: (value, row, index) => {
                  return (
                    <div>
                      <a href="javascript:void(0);" onClick={this.updateOption.bind(this, row)}>
                        编辑
                      </a>{' '}
                      |{' '}
                      <a href="javascript:void(0);" onClick={this.deleteOption.bind(this, row)}>
                        删除
                      </a>
                    </div>
                  );
                },
              },
            ],
          },
        });
      },
    });
  }

  deleteStock(row) {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'lastTrade/StockDelTrade',
      payload: row.id,
      callback: res => {
        that.dataSourceChange();
      },
    });
  }

  deleteOption(row) {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'lastTrade/DelCpbOptionTrade',
      payload: row.id,
      callback: res => {
        that.dataSourceChange();
      },
    });
  }

  updateOption(row) {
    const that = this;
    that.setState({
      row,
      updateOptionVisible: true,
    });
  }

  updateStock(row) {
    const that = this;
    that.setState({
      row,
      updateStockVisible: true,
    });
  }

  closeUpdateOptionVisbile() {
    const that = this;
    this.setState(
      {
        updateOptionVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }

  closeUpdateStockVisbile() {
    const that = this;
    this.setState(
      {
        updateStockVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }

  componentDidMount() {
    this.dataSourceChange();
  }

  componentWillUnmount() {}
}

export default LastTrade;
